<template>
    <el-dialog :close-on-click-modal="false" :title="mainTitleName()" v-model="visible" :width="900" custom-class="notpt"
    destroy-on-close @closed="$emit('closed')">
        <el-container>
            <audio ref="audio" :src="audio.src" controls class="audio" @ended="audio.status={}"></audio>
            <el-container class="is-vertical">
                <div class="panel-search-box" style="padding-left:0px;">
                    <div class="panel-search">
<!--                        <el-input v-model="search.word" placeholder="句子" clearable style="margin-left:0px;"></el-input>-->
                        <el-select v-model="search.status" placeholder="状态" clearable>
                            <el-option label="启用" :value="1"></el-option>
                            <el-option label="禁用" :value="0"></el-option>
                            <el-option label="音频转换中" :value="2"></el-option>
                        </el-select>
                        <el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
                        <el-button type="primary" icon="el-icon-plus" @click="add" v-if="permission.add">增加</el-button>
                        <el-button type="primary" icon="el-icon-download" @click="table_import" >导入</el-button>
<!--                        <el-button v-if="permission.delete" type="danger" plain icon="el-icon-delete" :disabled="!selection.length" @click="batch_delete">批量删除</el-button>-->
                    </div>
                </div>
                <el-main class="nopadding">
                    <scDialogTable ref="table" :apiObj="$API.course.grammarVocabulary.list" remoteSort :params="search" :height="500" @dataChange="dataChange" @selection-change="selectionChange"
                    :rowKey="getRowKeys">
                      <el-table-column type="selection" width="50" :reserve-selection="true"></el-table-column>
                      <el-table-column label="序号" prop="index" width="70" align="left"></el-table-column>
                      <el-table-column label="句子" show-overflow-tooltip  prop="word" align="center"></el-table-column>
                      <el-table-column label="句子音频" width="100" align="center">
                        <template #default="scope">
                          <div @contextmenu.prevent.native="openContextMenuStrip($event, scope.row, 'voice')">
                            <el-button v-if="audio.status[scope.row.id]" size="small" @click="pause(scope.row, 'voice')">暂停播放</el-button>
                            <el-button v-else size="small" @click="play(scope.row, 'voice')">播放音频</el-button>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column label="译文" show-overflow-tooltip prop="translation" align="center" width="150"></el-table-column>
                      <el-table-column label="状态" prop="status" width="120" align="center">
                        <template #default="scope">
                          <el-tag size="mini" v-if="scope.row.status == 0" type="danger">禁用</el-tag>
                          <el-tag size="mini" v-if="scope.row.status == 1" type="success">正常</el-tag>
                          <el-tag size="mini" v-if="scope.row.status == 2" type="warning">音频转换中</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="创建时间" prop="createdAt" width="150" align="center"></el-table-column>
                      <el-table-column label="操作" fixed="right" align="center" width="150">
                        <template #default="scope">
                          <el-button v-if="permission.edit" type="text" size="small" @click="table_edit(scope.row)">编辑</el-button>
<!--                          <el-divider v-if="permission.delete" direction="vertical"></el-divider>-->
<!--                          <el-popconfirm v-if="permission.delete" :title="'确认是否删除此句子?'" @confirm="table_del(scope.row)">-->
<!--                            <template #reference>-->
<!--                              <el-button type="text" size="small">删除</el-button>-->
<!--                            </template>-->
<!--                          </el-popconfirm>-->
                        </template>
                      </el-table-column>
                    </scDialogTable>
                </el-main>
            </el-container>
        </el-container>
    </el-dialog>

    <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>

    <import-dialog v-if="dialog.import" ref="importDialog" @success="handleSuccess" @closed="dialog.import=false" :courseId="course.courseId" :packageId="course.id" ></import-dialog>

</template>

<script>
import { rolePermission } from '@/utils/permission'
import saveDialog from './save.vue'
import importDialog from './import.vue'
import config from "@/config"
export default {
    components: {
        saveDialog,
        importDialog
    },
    data() {
        return {
            visible: false,
            selection: [],
            course: {},
            dialog: {
                save: false,
                import: false,
            },
            search: {
                name: null,
                package_id: null,
            },
            permission: {
                add: rolePermission('course-vocabulary-add'),
                edit: rolePermission('course-vocabulary-edit'),
                delete: rolePermission('course-vocabulary-delete'),
                import: rolePermission('course-vocabulary-import'),
            },
            audio: {
				src: '',
				status: {}
			},
            contextmenu: {
                visible: false,
                top: 0,
                left: 0,
                download: null,
            }
        }
    },
    watch: {
        'contextmenu.visible'(value) {
            if (value) {
                document.body.addEventListener('click', this.closeContextMenuStrip)
            } else {
                document.body.removeEventListener('click', this.closeContextMenuStrip)
            }
        }
    },
    mounted() {
    },
    methods: {
      GoGrammarContent(row){
        // console.log(row.id)
      },
        open(row) {
            this.visible = true
            this.course = row
            this.search.package_id = row.id
            return this
        },
        dataChange(res, tableData) {
			let total = res.data.total
            let perPage = res.data.perPage
            let page = (this.$refs.table && this.$refs.table.currentPage) || 1
            tableData.forEach((item, index) => {
				item.index = total - (page * perPage + index - perPage)
            })
        },
        getRowKeys(row) {
            return row.id
        },
        //添加
        add() {
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('add', this.course)
            })
        },
        //导入
        table_import() {
            this.dialog.import = true
            this.$nextTick(() => {
                this.$refs.importDialog.int()
            })
        },
        //编辑
        table_edit(row) {
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('edit', this.course).setData(row)
            })
        },
        //删除
        async table_del(row) {
            await this.$API.course.vocabulary.action.delete({ id: row.id }).then(() => {
                this.$refs.table.refresh()
                this.$notify.success("删除成功")
            })
        },
        //表格选择后回调事件
         selectionChange(selection) {
            this.selection = selection
        },
        //批量删除
        batch_delete() {
            this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
                type: 'warning'
            }).then(async () => {
                let idsArr = this.selection.map(item => { return item.id })
                await this.$API.course.vocabulary.batch.delete({ids: idsArr}).then(res => {
                    this.$notify.success("删除成功")
                    this.$refs.table.refresh()
                })
            }).catch(() => {

            })
        },
        // 搜索
        upsearch() {
            this.$refs.table.upData(this.search)
        },
        //本地更新数据
        handleSuccess() {
            this.$refs.table.refresh()
        },
        mainTitleName() {
            let titleName = '专题库管理';
            if (this.course.title) {
                titleName = `【${this.course.title}】专题库管理`;
            }
            return titleName;
        },
        play(row, type) {
            this.audio.status = {}
            let audio = ''
            if (type == 'voice') {
                audio = `https://yypx-1331574292.cos.ap-beijing.myqcloud.com/${row.voice_file}`
            }else if ('translationVoice') {
                audio = row.translationVoiceFile
            }
            if (audio) {
                this.audio.src = audio
                this.$nextTick(() => {
                    this.$refs.audio.play()
                    this.audio.status[row.id+'_'+type] = true
                })
            } else {
                this.$notify.error("没有音频")
            }
        },
        pause(row, type) {
            this.audio.status = {}
            this.audio.status[row.id+'_'+type] = false
            this.$refs.audio && this.$refs.audio.pause()
        },
        openContextMenuStrip(e, row, type) {
            console.log(222)
            if (this.contextmenu.visible) {
                this.closeContextMenuStrip()
            } else {
                this.contextmenu.top = e.pageY
                this.contextmenu.left = e.pageX
                this.contextmenu.visible = true
                let audio = ''
                if (type == 'voice') {
                     audio = row.voice_file
                }else if ('translationVoice') {
                     audio = row.translationVoiceFile
                }
                if (audio) {
                    this.contextmenu.download = audio.url
                }
            }
        },
        closeContextMenuStrip() {
            this.contextmenu.visible = false
            this.contextmenu.download = null
        }
    }
}
</script>

<style>
.audio {
    width: 0;
    height: 0;
    display: none;
}

/* dialog内上边距设置 */
.position {
    display: flex;
    align-items: center;
}
.position-item {
    margin-right: 5px;
}
.position-item:last-child {
    margin-right: 0;
}
/* dialog内上边距设置 END */
</style>
